package ar.com.ford.it.fullEconomics.logic;

import java.sql.Timestamp;
import java.util.Collection;
import ar.com.ford.it.fullEconomics.FullEconomicsPrs;
import ar.com.ford.it.fullEconomics.exception.FullEconomicsException;
import ar.com.ford.it.fullEconomics.persistence.dao.LogDao;
import ar.com.ford.it.fullEconomics.persistence.dao.WorkerFileDao;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx01Intfsource;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx02Fileconten;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx03Intflog;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesx04Intflevent;
import ar.com.ford.it.webengine.persistence.PersistenceUtil;
import com.ford.it.logging.ILogger;
import com.ford.it.logging.Level;
import com.ford.it.logging.LogFactory;
import com.ford.it.persistence.PersistenceException;

public class LogProcessLogic {
	private static final String CLASS_NAME = LogProcessLogic.class.getName();

	private static final ILogger log = LogFactory.getInstance().getLogger(
			CLASS_NAME);
    
    

	/**
	 * TEESX03_INTFLOG Record Definition Contains the Log of process
	 * transactions for a file, including the overall result of the transaction.
	 * 
	 * @param fileContent
	 * @param userId
	 * @throws FullEconomicsException
	 */
	public Teesx03Intflog insertLogInf(Teesx01Intfsource source, Teesx02Fileconten fileContent, String userId, String status,Timestamp logStart)
			throws FullEconomicsException {
		String METHOD_NAME = "InsertLogInf";
		log.entering(CLASS_NAME, METHOD_NAME);

		LogDao logDao = new LogDao();
		PlantLogic plant = new PlantLogic();
		
		Teesx03Intflog intflog = new Teesx03Intflog();
		try {
			PersistenceUtil.newTransaction();
			//intflog.setEesx01Intfsource((logObj.getEesx01Intfsource()));
			intflog.setEesx01Intfsource(source);
			
			String[] fieldsRestr = {"eesx01Intfsource"};
			Object[] valuesRestr = {source};
			//Object[] valuesRestr = {logObj.getEesx01Intfsource()};
			
			intflog.setEesx03IlogSequenceK(logDao.getMax(new Teesx03Intflog(),
					fieldsRestr, valuesRestr, "eesx03IlogSequenceK") + 1);
			intflog.setEesx03IlogStartM(new Timestamp(System
					.currentTimeMillis()));
			// Posibles estadosStatus of the Transaction Execution: "P"
			// (Pending), "C" (Cancelled), "R" (Running), "S" (Completed
			// Successfully), "W" (Completed with Warnings).
			intflog.setEesx03IlogProcStatusCodeC(status);
			// ID Key for locating the File record (if exists).
			intflog.setTeesx02Fileconten(fileContent);
			//LSPARACI : replaced by previous line
			//intflog.setEesx03IlogSequenceK(logObj.getEesx02FconSequenceK());
			intflog.setEesx03CreateProcessC(userId);
			intflog.setEesx03CreateS(new Timestamp(System.currentTimeMillis()));
			intflog.setEesx03LastUpdtProcessC(userId);
			intflog.setEesx03IlogStartM(logStart);
			intflog.setEesx03LastUpdtUserC(userId);
			intflog
					.setEesx03LastUpdtS(new Timestamp(System
							.currentTimeMillis()));
			intflog.setEesx03CreateUserC(userId);
			intflog.setEesx03CreateProcessC(userId);
			
			/**
			 * Verificar si estos datos se ingresan al comienzo del registro o
			 * despues. Puede que necesiten revision inicianlmente estos campos
			 * quedaran en nullo
			 */
			logDao.insertIntfLog(intflog);
			PersistenceUtil.commitTransaction();

		} catch (PersistenceException pe) {

			log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
					"PersistenceException", pe);
			try {
				PersistenceUtil.rollbackTransaction();
			} catch (PersistenceException rollbackEx) {
				rollbackEx.printStackTrace();
			}
			log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
					"Create Part Exception", pe);
			throw new FullEconomicsException(pe,
					FullEconomicsPrs.MessageErrors.Supply.CREATE);
		}
		return intflog;
	}
    
    public Teesx03Intflog getLastIntfLog(Teesx01Intfsource intfSource){
        LogDao dao = new LogDao();
        Teesx03Intflog intfLog = null;
        try {
            intfLog = dao.getLastIntfLog(intfSource);
        } catch (PersistenceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return intfLog;
    }
/**
 * Acutaliza el estado de log info tambien permite agregar la hora en que finalizo el log
 * @param intfLog
 * @param status
 * @param logEnd
 * @throws PersistenceException
 */
	public void updateLogInfo(Teesx03Intflog intfLog, String status, Timestamp logEnd) {
		Teesx03Intflog workingcopy = null;
		LogDao logDao = new LogDao();
		try {
			PersistenceUtil.newTransaction();
			PersistenceUtil.getPersistenceManager().clearCache();
			if(logEnd!=null){
				workingcopy = logDao.getIntflogyUpdate(intfLog);
				workingcopy.setEesx03LastUpdtS(new Timestamp(System
						.currentTimeMillis()));
				workingcopy.setEesx03IlogProcStatusCodeC(status);
				workingcopy.setEesx03IlogEndM(logEnd);
			}else{
				workingcopy = logDao.getIntflogyUpdate(intfLog);
				workingcopy.setEesx03LastUpdtS(new Timestamp(System
						.currentTimeMillis()));
				workingcopy.setEesx03IlogProcStatusCodeC(status);
			}
		PersistenceUtil.commitTransaction();
		} catch (PersistenceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * TEESX04_INTFLEVENT Contains the detailed events that aroused during the
	 * execution of a transaction.
	 * 
	 * @param userId
	 * @param idNumberR
	 * @param logSequenceR
	 * @param typeCodeC
	 * @param RecordNumberR
	 * @param messageDescripX
	 */
	public void insertLogIntfLevent(String userId,Teesx03Intflog intfLog, String typeCodeC, 
			String messageDescripX,int countLine) throws FullEconomicsException {
				
		// Llama a la misma funcion indicando -1 en secuencia de Evento.
		// de esta forma, el proceso buscara el numero maximo para ingresarse
		insertLogIntfLevent(userId,intfLog,typeCodeC,messageDescripX,countLine,-1);
	}
		
	/**
	 * TEESX04_INTFLEVENT Contains the detailed events that aroused during the
	 * execution of a transaction.
	 * 
	 * @param userId
	 * @param idNumberR
	 * @param logSequenceR
	 * @param typeCodeC
	 * @param RecordNumberR
	 * @param messageDescripX
	 * @param eventSeq
	 * @throws FullEconomicsException
	 */
	public void insertLogIntfLevent(String userId,Teesx03Intflog intfLog, String typeCodeC, 
			String messageDescripX,int countLine, int eventSeq) throws FullEconomicsException {
		String METHOD_NAME = "LogIntfLevent";
		log.entering(CLASS_NAME, METHOD_NAME);

		LogDao logDao = new LogDao();
		Teesx04Intflevent intLevent = new Teesx04Intflevent();
		
		try {
			
			PersistenceUtil.newTransaction();
			
			// Segun parametro eventSeq, toma la secuencia indicada 
			// o bien va a buscar el maximo + 1
			if (eventSeq == -1) {
				eventSeq = logDao.getMaxEventSeq(intfLog)+1;
			}
						
			intLevent.setTeesx03Intflog(intfLog);
			intLevent.setEesx04IevntSequenceK(eventSeq);
			intLevent.setEesx04IevntTimeM(new Timestamp(System
					.currentTimeMillis()));

			intLevent.setEesx04IevntMessageDescripX(messageDescripX);
			intLevent.setEesx04IevntTypeCodeC(typeCodeC);
			intLevent.setEesx04IevntRecordNumberR(countLine);
			// Verificar estos datos no iran estos pero preguntar a luciano que
			// es lo que ira
			intLevent.setEesx04LastUpdtS(new Timestamp(System
					.currentTimeMillis()));
			intLevent
					.setEesx04CreateS(new Timestamp(System.currentTimeMillis()));
			intLevent.setEesx04LastUpdtUserC(userId);
			intLevent.setEesx04CreateUserC(userId);
			logDao.insertIntfleEvent(intLevent);
			PersistenceUtil.commitTransaction();
		} catch (PersistenceException pe) {

			log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
					"PersistenceException", pe);
			try {
				PersistenceUtil.rollbackTransaction();
			} catch (PersistenceException rollbackEx) {
				rollbackEx.printStackTrace();
			}
			log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
					"Create Part Exception", pe);
			throw new FullEconomicsException(pe,
					FullEconomicsPrs.MessageErrors.Supply.CREATE);
		}
	}

	/**
	 * TEESX02_FILECONTEN Record Definition Contains all the files that are
	 * received or that are generated for export, including a field with the
	 * whole content of it.
	 * 
	 * @param userId
	 * @param idNumberR
	 * @param generationDateM
	 * @param contentBlob
	 * @param contentSizeQ
	 * @throws FullEconomicsException
	 */
	public Teesx02Fileconten insertLogFileConten(String userId,
			String fullPathFile, Timestamp generationDateM, String contentBlob,
			int contentSizeQ) throws FullEconomicsException {
		String METHOD_NAME = "LogFileConten";
		log.entering(CLASS_NAME, METHOD_NAME);

		LogDao logDao = new LogDao();
		Teesx02Fileconten intFileconten = new Teesx02Fileconten();

		try {
			PersistenceUtil.newTransaction();
			intFileconten.setEesx01Intfsource(logDao
					.getIntfSource(fullPathFile));
			intFileconten
					.setEesx02FconSequenceK(logDao.getMax(
							new Teesx02Fileconten(), null, null,
							"eesx02FconSequenceK") + 1);
			// Datos aun no preveedios
			intFileconten.setEesx02FconContentBlobO(contentBlob);
			intFileconten.setEesx02FconContentSizeQ(contentSizeQ);
			intFileconten.setEesx02FconGenerationDateM(generationDateM);
			// Creo que se hace una unica ves verificar
			intFileconten.setEesx02CreateS(new Timestamp(System
					.currentTimeMillis()));
			intFileconten.setEesx02CreateUserC(userId);
			// Si no existe el file tendria que actalizar solo esto.
			intFileconten.setEesx02LastUpdtUserC(userId);
			intFileconten.setEesx02LastUpdtS(new Timestamp(System
					.currentTimeMillis()));

			logDao.insertFileConten(intFileconten);
			PersistenceUtil.commitTransaction();
		} catch (PersistenceException pe) {

			log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
					"PersistenceException", pe);
			try {
				PersistenceUtil.rollbackTransaction();
			} catch (PersistenceException rollbackEx) {
				rollbackEx.printStackTrace();
			}
			log.logp(Level.SEVERE, CLASS_NAME, METHOD_NAME,
					"Create Part Exception", pe);
			throw new FullEconomicsException(pe,
					FullEconomicsPrs.MessageErrors.Supply.CREATE);
		}
		return intFileconten;
	}
    
    public Teesx02Fileconten getFileContent(Teesx01Intfsource intfSource){
        String METHOD_NAME = "LogFileConten";
        log.entering(CLASS_NAME, METHOD_NAME);
        LogDao logDao = new LogDao();
        Teesx02Fileconten fileContent = new Teesx02Fileconten();
        fileContent.setEesx01Intfsource(intfSource);
        
        String[] fields = {"eesx01Intfsource"};
        Object[] values = {intfSource};
        try {
            Integer max = logDao.getMax(new Teesx02Fileconten(), fields, values, "eesx02FconSequenceK");
            fileContent.setEesx02FconSequenceK(max);
            fileContent = (Teesx02Fileconten) logDao.getObjById(fileContent);
        } catch (PersistenceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return fileContent;
    }
    
    public Collection<Teesx02Fileconten> getFileContentsByStatus(String status, 
    		Teesx01Intfsource intfSource, Timestamp dateFrom, Timestamp dateTo) {
    	
	   	String METHOD_NAME = "getfileContentsByStatus";
		log.entering(CLASS_NAME, METHOD_NAME);    	
    	
    	Collection<Teesx02Fileconten> resultCol = null;

    	WorkerFileDao fileDao = new WorkerFileDao();
    	
    	try {
    		
    	   resultCol = fileDao.findFilesByProcessStatus(status, intfSource, dateFrom, dateTo);
    	   
        } catch (PersistenceException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    	
		log.exiting(CLASS_NAME, METHOD_NAME);    	
    	
    	return resultCol;
    }
}
